package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConfirmReceiver {

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.confirm", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm"),
            key = {"routing.confirm"}
    ))
    public void getMsg(String msg, Message message, Channel channel) {
        try {
            System.out.println("接收到的消息：\t"+new String(message.getBody()));
            System.out.println("接收到的消息：\t"+msg);
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            //  false: 表示一个一个的确认，true 表示批量确认消息！
            // 采用手动应答模式, 手动确认应答更为安全稳定
            //如果手动确定了，再出异常，mq不会通知；如果没有手动确认，抛异常mq会一直通知
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 第二个参数： false: 表示一个一个的确认，true 表示批量确认消息！
            // 第三个参数：是否重回队列！
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
